<template>
  <div>
    <el-container>
      <!--  头部    -->
      <br>
      <br>
      <br>
      <br>
      <el-header>

      </el-header>


      <!--  中    -->
      <el-main>
        <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange">
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              prop="productname"
              label="商品"
              width="250">
            <template slot-scope="scope" src="">
              <!--scope.row得到当前行对应的数组里面的对象-->
              <img :src="scope.row.picture" width="60%" alt="">

            </template>

          </el-table-column>
          <el-table-column
              width="250">
            <template slot-scope="scope" src="">
              {{ scope.row.productname }}
            </template>
          </el-table-column>
          <el-table-column
              prop="buyname"
              label="数量"
              width="270">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.buynum" @change="handleChange" :min="1" :max="10" label=""></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
              prop="price"
              label="单价"
              width="180">
          </el-table-column>
          <el-table-column
              prop="totalPrice"
              label="金额"
              width="180">
            <template slot-scope="scope">￥{{scope.row.buynum*scope.row.price}}</template>
          </el-table-column>
          <el-table-column
              label="操作"
              show-overflow-tooltip>
            <template slot-scope="scope">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteConfirm(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px">
<!--          <el-button @click="toggleSelection([tableData[1], tableData[2]])">切换第二、第三行的选中状态</el-button>-->
          <el-button @click="toggleSelection()">取消选择</el-button>
          商品总计（不含运费）：<span style="font-size: 32px;color:#f81240;">￥{{total}}</span>
          <el-button type="primary" style="display: block;margin-left: 1000px;margin-top: -39px" @click="buy()">去结算</el-button>
        </div>
      </el-main>

      <el-footer>

      </el-footer>
    </el-container>
  </div>
</template>
<script>


export default {
  data() {
    return {
      total: 0,
      tableData:[],
      multipleSelection: [],
      cartId: '',
      order:{
        userid:"",
        productid:"",
        productname:"",
        picture:"",
        buynum:"",
        price:"",
        address:"达内科技有限公司",
        total:"",
        tablename:"童装",
        consignee:"刘欢",
        phone:"10086"
      }
    }
  },
  methods: {
    buy(){
      let jwt=localStorage.getItem("jwt");
      const decode = this.jwt_decode(jwt);
      this.order.userid=decode.id;
      this.multipleSelection.forEach((item)=>{
        this.cartId=item.id;
        this.order.buynum=item.buynum;
        this.order.productid=item.productid;
        this.order.productname=item.productname;
        this.order.picture=item.picture;
        this.order.buynum=item.buynum;
        this.order.price=item.price;
      });
      this.order.total=this.total;
      console.log(this.order);
      let url = "http://localhost:8090/orders/add-new";
      console.log("url="+url);
      let formData = this.qs.stringify(this.order);
      console.log('formData：' + formData);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url,formData).then((response)=>{
        let responseBody = response.data;
        console.log(responseBody);
        if (responseBody.state == 20000){
          console.log('加入订单成功');
          let url = "http://localhost:8090/cart/"+this.cartId +"/delete";
          console.log("url="+url);
          this.axios
              .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
              .post(url).then((response) => {
            let responseBody = response.data;
            console.log(responseBody);
            if (responseBody.state == 20000) {
              console.log('删除成功');
              this.loadCartList();
            } else {
              this.$message.error(responseBody.message);
            }
          });
          location.href="/index/order";
        }else {
          this.$message.error(responseBody.message);
        }
        this.loadCartList();
      })
    },
    deleteConfirm(tableData){
      let title = '提示'
      let message = '此操作将永久删除 '+tableData.productname+ ' ,是否继续?';
      this.$confirm(message,title,{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        type:'warning'
      }).then(() => {
        this.handleDelete(tableData);
      }).catch(() => {

      });
    },
    handleDelete(cart) {
      console.log('handleDelete..  id=' + cart.id)
      let url = "http://localhost:8090/cart/"+cart.id+"/delete";
      console.log("url="+url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) =>{
        let responseBody = response.data;
        console.log(responseBody);
        if (responseBody.state == 20000){
          console.log('删除成功');
          this.loadCartList();
        }else {
          this.$message.error(responseBody.message);
        }
        this.loadCartList();
      })
    },
    handleChange(value) {
      console.log(value);
      return value;
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection= val;
      this.total=0;
      console.log(this.multipleSelection)
      this.multipleSelection.forEach((cart)=>{
        this.total+=(cart.buynum*cart.price);
        console.log(this.total)
      })
    },
    loadCartList(){
      console.log('loadCartList..')
      let jwt=localStorage.getItem("jwt");
      const decode = this.jwt_decode(jwt);
      console.log(decode.id);
      let url = "http://localhost:8090/cart/"+decode.id;
      console.log("url="+url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) =>{
        console.log(response);
        let responseBody = response.data;
        console.log("!!!!"+responseBody.cartData);
        this.tableData = responseBody.data;
      });
    }
  },
  mounted() {
    console.log("mounted..")
    this.loadCartList();
  }
}
</script>



